/**
 * 
 */
package com.nercel.dsj.gksales.api.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.nercel.dsj.gksales.thirdparty.wxpay.util.MyX509TrustManager;
import com.nercel.dsj.gksales.thirdparty.wxpay.util.WeChatCommonUtil;
import com.nercel.dsj.gksales.thirdparty.wxservercode.config.WxServerCodeConfig;
import com.nercel.dsj.gksales.thirdparty.wxservercode.entity.WxServerCodeAccessTokenEntity;
import com.nercel.dsj.gksales.thirdparty.wxservercode.service.WxServerCodeService;

/**
 * @author qinshuangxi
 * @date 2020年6月28日
 * 
 */
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 微信相关操作
 */

@RestController
@RequestMapping("/api/v1/weChat")
@Api(tags = "微信相关操作")
@Slf4j
public class WeChatController {

	@Autowired
	private StringRedisTemplate redisTemplate;

	@Autowired
	private WxServerCodeService wxServerCodeService;

	@Autowired
	private RestTemplate restTemplate;

	/**
	 * 验证微信后台配置的服务器地址有效性
	 * <p>
	 * 接收并校验四个请求参数
	 *
	 * @param url       URL
	 * @param timestamp 时间戳
	 * @param ticket    ticket
	 * @param echostr   随机字符串
	 * @return echostr
	 */
	@ApiOperation(value = "获取签名")
	@GetMapping("/getSignature")
	public Map<String, String> checkName(@ApiParam(value = "url") @RequestParam(name = "url") String url,
			@ApiParam(value = "时间戳") @RequestParam(name = "timestamp", required = false) String timestamp,
			@ApiParam(value = "ticket") @RequestParam(name = "ticket", required = false) String ticket,
			@ApiParam(value = "echostr") @RequestParam(name = "echostr", required = false) String echostr) {

		if (StringUtils.isBlank(timestamp)) {
			timestamp = String.valueOf(System.currentTimeMillis() / 1000);
		}
		if (StringUtils.isBlank(echostr)) {
			echostr = RandomStringUtils.randomAlphanumeric(10);
		}
		if (StringUtils.isBlank(ticket)) {
			JSONObject jsonObject = getTicket("");
			ticket = jsonObject.getString("ticket");
		}
		log.info("微信-开始校验签名");
		log.info("收到来自微信的 echostr 字符串:{}", echostr);

		/*
		 * 加密/校验流程如下: 1. 将token、timestamp、nonce三个参数进行字典序排序 2. 将三个参数字符串拼接成一个字符串进行sha1加密
		 * 3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
		 */
		log.info("微信-开始排序");
		// 1.排序
		url = URLDecoder.decode(url);
		String sortString = sort(url, timestamp, ticket, echostr);
		log.info("微信-开始sha1加密");
		// 2.sha1加密
		String signature = sha1(sortString);
		// 工具类的加密方法
		// String signature = DigestUtils.sha1Hex(sortString);
		Map<String, String> map = new HashMap<>();
		map.put("appId", WxServerCodeConfig.app_id);
		map.put("url", url);
		map.put("timestamp", timestamp);
		map.put("ticket", ticket);
		map.put("echostr", echostr);
		map.put("str", sortString);
		map.put("signature", signature);
		return map;
	}

	@GetMapping("/getTicket")
	public JSONObject getTicket(@RequestParam(value = "accessToken", required = false) String accessToken) {
		// 使用redis缓存
		if (redisTemplate.hasKey("weixin:jsapi_ticket")) {
			JSONObject jsonObject = new JSONObject();
			String ticket = redisTemplate.opsForValue().get("weixin:jsapi_ticket");
			Long expiresIn = redisTemplate.getExpire("weixin:jsapi_ticket", TimeUnit.SECONDS);
			jsonObject.put("ticket", ticket);
			jsonObject.put("expires_in", Math.toIntExact(expiresIn));
			jsonObject.put("errcode", 0);
			jsonObject.put("errmsg", "OK");
			return jsonObject;
		}
		if (StringUtils.isNotBlank(accessToken)) {
			redisTemplate.opsForValue().set("weixin:access_token", accessToken, 5400L, TimeUnit.SECONDS);
			return WeChatCommonUtil.getTicket(accessToken);
		}
		accessToken = getToken().getString("access_token");
		JSONObject jsonObject = WeChatCommonUtil.getTicket(accessToken);
		redisTemplate.opsForValue().set("weixin:jsapi_ticket", jsonObject.getString("ticket"),
				jsonObject.getLong("expires_in"), TimeUnit.SECONDS);
		return jsonObject;
	}

	public JSONObject getToken() {
		// 使用redis缓存
		if (redisTemplate.hasKey("weixin:access_token")) {
			JSONObject jsonObject = new JSONObject();
			String accessToken = redisTemplate.opsForValue().get("weixin:access_token");
			Long expiresIn = redisTemplate.getExpire("weixin:access_token", TimeUnit.SECONDS);
			log.info("从redis中获取token相关信息：access_token:{},expiresIn:{}", accessToken, expiresIn);
			jsonObject.put("access_token", accessToken);
			jsonObject.put("expires_in", expiresIn);
			return jsonObject;
		}
		JSONObject jsonObject = WeChatCommonUtil.getToken(WxServerCodeConfig.app_id, WxServerCodeConfig.app_secret);
		System.out.println(jsonObject.toJSONString());
		redisTemplate.opsForValue().set("weixin:access_token", jsonObject.getString("access_token"),
				5400L, TimeUnit.SECONDS);
		log.info("redis中取不到token信息，从微信平台取token相关信息：access_token:{},expiresIn:{}", jsonObject.getString("access_token"),
				jsonObject.getLong("expires_in"));
		return jsonObject;
	}

	public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			conn.setSSLSocketFactory(ssf);

			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			conn.setRequestMethod(requestMethod);

			// 当outputStr不为null时向输出流写数据
			if (null != outputStr) {
				OutputStream outputStream = conn.getOutputStream();
				// 注意编码格式
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 从输入流读取返回内容
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}

			// 释放资源
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			conn.disconnect();
			jsonObject = JSONObject.parseObject(buffer.toString());
		} catch (ConnectException ce) {
			log.error("连接超时：{}", ce);
		} catch (Exception e) {
			log.error("https请求异常：{}", e);
		}
		return jsonObject;
	}

	/**
	 * @Param [signature, timestamp, ticket, echostr]
	 * @Return java.lang.String
	 * @Description: 对所有待签名参数按照字段名的ASCII 码从小到大排序
	 */
	public String sort(String url, String timestamp, String ticket, String echostr) {
		return "jsapi_ticket=" + ticket + "&noncestr=" + echostr + "&timestamp=" + timestamp + "&url=" + url;
	}

	/**
	 * @Param [str]
	 * @Return java.lang.String
	 * @Description: 将字符串进行sha1加密
	 */
	public String sha1(String str) {
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-1");
			digest.update(str.getBytes());
			byte messageDigest[] = digest.digest();
			// 创建 16进制字符串
			StringBuffer hexString = new StringBuffer();
			// 字节数组转换为 十六进制 数
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
		AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
		cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
		// 解析解密后的字符串
		return new String(cipher.doFinal(encData), "UTF-8");
	}

	/**
	 * 根据code来获取用户基本信息(UnionID机制) 接口url
	 * https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
	 */
	@SuppressWarnings("unchecked")
	@ApiOperation(value = "获取用户基本信息(UnionID机制)")
	@GetMapping("/getUserInfoUnionID")
	public Map<String, Object> getUserInfoUnionID(@ApiParam(value = "code") @RequestParam(name = "code") String code) {
		try {
			String tokenUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESSTOKEN&openid=OPENID&lang=zh_CN";
			String accessToken = getToken().getString("access_token");
			log.info("获取用户基本信息(UnionID机制),取到token:{}", accessToken);
			WxServerCodeAccessTokenEntity wxServerCodeAccessTokenEntity = wxServerCodeService
					.getAccessTokenInfoByCode(code);
			String openId = wxServerCodeAccessTokenEntity.getOpenId();
			log.info("获取用户基本信息(UnionID机制),取到openId:{}", openId);
			String url = tokenUrl.replace("ACCESSTOKEN", accessToken).replace("OPENID", openId);
			Map<String, Object> map = restTemplate.getForObject(url, Map.class);
			// 如果发生token过期了情况，就清一次缓存中的token信息，然后重新获取token
			if (map.get("errcode") != null) {
				log.info("当前token到期时间为：{}", redisTemplate.getExpire("weixin:access_token", TimeUnit.SECONDS));
				redisTemplate.delete("weixin:access_token");
				accessToken = getToken().getString("access_token");
				url = tokenUrl.replace("ACCESSTOKEN", accessToken).replace("OPENID", openId);
				return restTemplate.getForObject(url, Map.class);
			}
			return map;
		}catch (Exception e){
			Map<String, Object> result = new HashMap<>();
			result.put("errcode", 500);
			return result;
		}
	}
}
